package com.snopy.concurrency.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author snopy
 * @version 1.0.0
 * @classname LockCas
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/28 21:58
 */
@Slf4j
public class LockCas {
    private AtomicInteger state = new AtomicInteger(0);
    private void lock(){
        while (true){
            if (state.compareAndSet(0,1)){
                break;
            }
        }
    }
    private void unlock(){
        log.debug("{} unlock...",Thread.currentThread().getName());
        state.set(0);
    }

    public static void main(String[] args) {
        LockCas lock = new LockCas();
        new Thread(()->{
            log.debug("t1 begin...");
            lock.lock();
            try{
                log.debug("t1 locked...");
                TimeUnit.SECONDS.sleep(3);
            }catch (InterruptedException ignore){}finally {
                log.debug("t1 end...");
                lock.unlock();
            }
        },"t1").start();
        new Thread(()->{
            log.debug("t2 begin...");
            lock.lock();
            try{
                log.debug("t2 locked...");
                TimeUnit.SECONDS.sleep(3);
            }catch (InterruptedException ignore){}finally {
                log.debug("t2 end...");
                lock.unlock();
            }
        },"t2").start();

    }
}
